<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once("Core.php");
class CI_User extends CI_Core{
	private $table ='user';
	function __construct(){
		parent::__construct();
		$this->database('default');
	}
	//获取会员信息
	public function getByOpendId($openid){
		if(!$openid) return $this->status(false,array());
		$rs = $this->get_one('*',array('openid'=>$openid),'user');
		return $this->status(true,$rs);
	}
	//自由查询
	public function pub_search($tj=array(),$tj2=array()){
		$arr = $this->get_all('*',$tj,'user',$tj2);
		return $this->status(true, $arr);
	}
	public function getByName($username){
		if(!$username) return $this->status(false,array());
		$rs = $this->get_one('*',array((stristr($username,'@')?'email':'username')=>$username),'user');
		return $this->status($rs==array()?false:true,$rs);
	}

	//获取企业信息
	public function getUserInfo($id){
		$id=$id?$id:$this->ci->input->get('id');
		$rs = $this->get_one('*',array('user_id'=>$id),'user_info');
		#echo '<pre>';print_R($rs);exit;
		$user_info = $this -> get_one('vender',array('id'=>$id),'user');
		$rs['shop_name'] = $user_info['vender'];
		return $this->status($rs==array()?false:true,$rs);
	}
	
	// 获取用户所有信息
	public function getUserAllInfoBy($id){
		$data = $this->get_all('*',array('b.id' => $id),'user',array('join'=>'user_info','on'=>'b.id=a.user_id'));
		return $data[0];
	}
	
	//更新OPENID
	public function updateOpenId($id,$openid){
		$this->db->update('user',array('openid'=>$openid),array('id'=>$id));
		return $this->status(true);
	}
	//更新绑定会员
	public function updateBindUser($id,$row){

		$this->db->update('user',$row,array('id'=>$id));
		return $this->status(true);
	}
	//会员列表
	public function getlist($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('user');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$arr=array();
		foreach($data['result'] as $v){
			$a = $this->get_one('name',array('id'=>$v['grade']),'user_class');
			$arr[]=array(
				'id'       	=>$v['id'],
				'user_id'	=> $v['user_id'],
				'username' 	=>$v['username'],
				'type' 		=>$v['type'],
				'verify_status'=>$v['verify_status'],
				'vender' 	=>$v['vender'],
				'email'    	=>$v['email'],
				'phone'    	=>$v['phone'],
				'china_id' 	=>$v['china_id'],
				'card_id'  	=>$v['card_id'],
				'scores'   	=>$v['scores'],
				'money'    	=>$v['money'],
				'addtime'  	=>date('Y-m-d H:i:s',$v['addtime']),
				'headimg'  	=>$v['headimg'],
				'is_subscribe'=>$v['is_subscribe'],
				'source'   	=>$v['source'],
				'grade'    	=>$a['name'],
				'gg_sort_order' => $v['gg_sort_order'],
				'sheng'		=> $v['sheng'],
				'shi'		=> $v['shi'],
				'qu'		=> $v['qu'],
				'logo'		=> $v['logo'],
			);
		}
		//$arr = $this -> sortArrByField($arr,'gg_sort_order');
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$arr);
	    return $this->status(true, $rs);
	}
	// 根据某个字段进行排序
	function sortArrByField(&$array, $field, $desc = false){
		$fieldArr = array();
		foreach ($array as $k => $v) {
			$fieldArr[$k] = $v[$field];
		}
		$sort = $desc == false ? SORT_ASC : SORT_DESC;
		array_multisort($fieldArr, $sort, $array);
		return $array;
	}
	//创建会员
	public function create($row){
		$arr = $this->get_one('id',array('username'=>$row['username']),'user'); 
		if($arr!=array()) return $this->status(false,'user_error'); //会员名已经存在 $arr['id']
		if($row['email']){
			$arr = $this->get_one('id',array('email'=>$row['email']),'user');
			if($arr!=array()) return $this->status(false,'email_error'); //邮箱已经存在
		}
		$userArr = array(
			'username' => $row['username'],
			'phone' => $row['username'],
			'type' => $row['type'],
			'openid'   => $row['openid'],
			'password' => $row['password'],
			'nickname' => $row['nickname'],
			//'sex'      => $row['sex'],
			'address'  => $row['address'],
			'headimg'  => $row['headimg'],
			'email'    => $row['email'],
			'belong_site'=> $row['belong_site'],
			'addtime'  => time(),
			'card_id'  => sprintf("%u",crc32(uniqid())),
			'source'   => $row['source'],
			'upline_id'=>$row['upline_id'],
			'type'=>$row['type'],
			//'offline_num'=>$row['offline_num']+1,
		);
		if($row['is_subscribe']) $userArr['is_subscribe'] = $row['is_subscribe'];
		$this->db->insert('user',$userArr);
		$new_id=$this->db->insert_id();
		//插入会员统计表
		$this->db->insert('user_statistics',array('user_id'=>$new_id));
		$this->db->insert('user_info',array('user_id'=>$new_id)); //企业资料表
		$this->ci->load->library('Huashang/system');
		//$settings = array_pop($this->ci->system->settings());
		$jf=$this->get_one("*", array('type'=>1),'user_scores_rule');
		if($jf['scores']>0) $this->addScoreRecord($row['username'],$jf['scores'],'注册会员赠送积分',1);
		//判断上线是否存在 是就送上线积分
		if($row['upline_id']){
			$u = $this->get_one('id,username',array('id'=>$row['upline_id']),'user'); 
			if($u!=array()){
				$jf=$this->get_one("*", array('type'=>4),'user_scores_rule');
				$this->addScoreRecord($u['username'],$jf['scores'],'推广下线增送积分',4);
			}
		}
		return $this->status(true,$new_id);
	}
	//更新会员资料
	public function update($id){
		$id=$id?$id:$this->ci->input->get('id');
		$rs = $this->get_one('*',array('id'=>$id),'user');
		return $this->status(true, $rs);
	}
	
	//删除会员
	public function remove($id){
		$id=$id?$id:explode(',', $this->ci->input->post('id'));
		$this->db->where_in('id', $id);
		$this->db->delete('user');
		
		$this->db->where_in('user_id', $id);
		$this->db->delete('user_statistics');
		
		$this->db->where_in('username', $id);
		$this->db->delete('user_address');
	}
	//会员登录
	public function login($username,$password){
		$rs = $this->get_one('id,username,password,email,card_id,openid,type',array((stristr($username,'@')?'email':'username')=>$username),'user');
		if($rs==array()) return $this->status(false,array());
		if($rs['password']!=md5($password)) return $this->status(false,array());
		return $this->status(true,$rs);
	}
	//保存会员资料
	public function saveRow($row){
		if(!$row['id']) $this->status(false,'ID is not valid!');
		$this->db->update('user',$row,array('id'=>$row['id']));
		return $this->status(true);
	}
	
	// 修改密码
	public function changePassWord($username,$password){
		if(empty($username) || empty($password)){
			return false;
		}
		$this->db->update('user',array('password' => md5($password)),array('username'=>$username));
		return true;
	}
	/***保存详细信息**/
	public function saveInfoRow($row,$info){
		if(!$row['id']) $this->status(false,'ID is not valid!');
		if($row!=array()) $this->db->update('user',$row,array('id'=>$row['id']));
		#echo '<pre>';print_R($row);exit;
		$this->db->update('user_info',$info,array('user_id'=>$row['id']));
		return $this->status(true);
	}
	//检测会员积分
	//保存常用地址
	public function saveAddress($row){
		if($row['is_default']==2) $this->db->update('user_address',array('is_default'=>1));
		if(!$row['id']) $this->db->insert('user_address',$row);
		else $this->db->update('user_address',$row,array('id'=>$row['id']));
		return $this->status(true);
	}
	
	// 设置默认地址
	public function setDefaultAddress($addr_id,$username){
		
		if(empty($addr_id) || !is_numeric($addr_id) || empty($username)){
			return false;
		}else{
			$this->db->update('user_address',array('is_default'=>2),array('username' => $username));
			$this->db->update('user_address',array('is_default'=>1),array('id'=>$addr_id,'username' => $username));
			return false;
		}
	}
	//设置默认地址
	public function saveDefaultAdd($id){
		if(!$id) return false;
		$this->db->update('user_address',array('is_default'=>1));
		$this->db->update('user_address',array('is_default'=>2),array('id'=>$id));
	}
	//删除常用地址
	public function delAddress($id){
		$this->db->where_in('id',$id);
		$this->db->delete('user_address');
	}
	//删除
	public function dropAddress($user_name,$id){
		if(empty($user_name) || empty($id) || !is_numeric($id)){
			
			return false;
		}
		$this->db->where('id',$id);
		$this->db->where('username',$user_name);
		$this->db->delete('user_address');
		return true;
	}
	//获取一条常用地址
	public function getOneAddress($id){
		$rs = $this->get_one('*',array('id'=>$id),'user_address');
		return $this->status(true,$rs);
	}
	//获取地址
	public function getAddress($username){
		$rs=array();
		if($username) $rs = $this->get_all('*',array('username'=>$username),'user_address',array('orderby' => array('id' => 'desc')));
		return $this->status(true,$rs);
	}
	//保存常用联系人
	public function saveContact($row){
		if(!$row['id']) $this->db->insert('user_contacts',$row);
		else $this->db->update('user_contacts',$row,array('id'=>$row['id']));
		return $this->status(true);
	}
	
	// 获取默认地址
	public function getDefaultAddr($username){
		if(empty($username)){
			return false;
		}
		return $this->status(true,$this -> get_one('*',array('username'=>$username,'is_default'=>1),'user_address'));
	}
	
	//获取常用地址
	public function getContact($username){
		$rs = $this->get_all('*',array('username'=>$username),'user_contacts');
		return $this->status(true,$rs);
	}
	//获取默认收件人
	public function getDefaultRecipient($username){
		if(!$username) return $this->status(false,array());
		$rs = $this->get_one('*',array('username'=>$username,'is_default'=>2),'user_address');
		if($rs!=array()) return $this->status(true,$rs);
		else{
			$rs = $this->get_one('*',array('username'=>$username),'user_address');
			return $this->status(true,$rs);
		}
	}
	//写入积分记录(会员名,积分额,简要)
	public function addScoreRecord($username,$total,$intro,$type=1,$source_id=''){
		$row = $this->get_one('*',array('username'=>$username),'user');
		if($row==array()) return $this->status(false,'User is not existed!');
		if($total<0){
			if($row['scores']<abs($total)) return $this->status(false, 'scores_error');
		}
		$row['scores']+=$total;
		//更新积分总额
		$this->db->update('user',array('scores'=>$row['scores']),array('id'=>$row['id']));
		//写入积分记录表
		$this->db->insert('user_score_records',array(
			'username' => $username,
			'intro'    => $intro,
			'total'    => $total,
			'remain'   => $row['scores'],
			'type' => $type,
			'source_id'=>$source_id,
			'addtime'  => time(),
		));
		return $this->status(true,array('total'=>$total,'remain'=>$row['scores']));
	}
	//获取积分记录
	public function getScoreRecords($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('user_score_records');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true, $rs);
	}
	
	//删除积分记录
	public function delScore(){
		$id=$id?$id:explode(',', $this->ci->input->post('id'));
		$this->db->where_in('id', $id);
		$this->db->delete('user_score_records');
	}
	//获取分成记录
	public function getUserCommList($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('user_rebate_records');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true, $rs);
	}
	//删除分成记录
	public function delUserCommList(){
		$id=$id?$id:explode(',', $this->ci->input->post('id'));
		$this->db->where_in('id', $id);
		$this->db->delete('user_rebate_records');
	}
	//获取会员返利配置
	public function userComm(){
		$rs = $this->get_all('*',array(),'user_set_rebate');
		return $this->status(true, $rs);
	}
	//保存返利配置
	public function saveUserComm($ids,$jfs){
		foreach($ids as $k=>$v){
			$this->db->update('user_set_rebate',array('shoping_rebate'=>$jfs[$k]),array('id'=>$v));
		}
	}
	//会员充值
	public function recharge($order_sn,$trade_no){
		if(!$order_sn) return $this->status(false, 'order_sn is null');
		$rs=$this->get_one('*',array('order_sn'=>$order_sn),'user_asset');
		if($rs!=array()){
			$u=$this->get_one('money',array('id'=>$rs['user_id']),'user');
			$this->db->update('user',array('money'=>$u['money']+$rs['total']),array('id'=>$rs['user_id']));
			$this->db->update('user_asset',array('status'=>1,'remain'=>$u['money']+$rs['total'],'trade_no'=>$trade_no),array('order_sn'=>$order_sn));
			return $this->status(true, 'trade suess');
		}else{
			return $this->status(false, 'trade not find');
		}
	}
	//修改充值记录
	public function updateTrade($row){
		$this->db->update('user_asset',$row,array('order_sn'=>$row['order_sn']));
		
	}
	//获取一条充值记录
	public function getRecharge($order_sn){
		if(!$order_sn) return $this->status(false, 'order_sn is null');
		$rs=$this->get_one('*',array('order_sn'=>$order_sn),'user_asset');
		return $this->status(true, $rs);
	}
	//会员卡消费
	public function userPay($total,$user_id,$order_sn){
		if(!$user_id) return $this->status(false, 'U1000');
		$u=$this->get_one('*',array('id'=>$user_id),'user');
		if($u==array()) return $this->status(false, 'U1001');
		if($u['money']<$total){
			return $this->status(false,'U1002');
		}
		$this->db->update('user',array('money'=>$u['money']-$total),array('id'=>$user_id));
		$this->db->insert('user_asset',array(
			'order_sn'=> sprintf("%u",crc32(uniqid())),
			'type'=>2,
			'user_id'=>$u['id'],
			'user_name'=>$u['user_name'],
			'total'=>$total,
			'remain'=>$u['money']-$total,
			'status'=>1,
			'intro'=>'购物消费',
			'add_time'=>time(),
			'source_order_sn'=>$order_sn
		));
		return $this->status(true, 'trade suess');
	}
	//插入充值或消费记录
	public function inserTrade($v){
		if($v['user_id']=='') return $this->status(false, '用户无效');
		$this->db->insert('user_asset',array(
			'order_sn' =>$v['order_sn'],
			'trade_no' =>'',
			'type'     =>$v['type'],
			'user_id'  =>$v['user_id'],
			'user_name'=>$v['user_name'],
			'total'    =>$v['total'],
			'remain'   =>$v['remain'],
			'intro'    =>$v['intro'],
			'pay_wechat'=>$v['pay_wechat'],
			'add_time' =>time(),
		));
	}
	//获取帐单
	public function getAsset($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('user_asset');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true, $rs);
	}
	//获取会员消息
	public function getInbox($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('message');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true, $rs);
	}
	//获取一条
	public function getInboxId($id){
		$rs=$this->get_one('*',array('id'=>$id),'message');
		return $this->status(true,$rs);
	}
	//删除会员消息
	public function deleteInbox($id){
		$this->db->where_in('id',explode(',', $id));
		$this->db->delete('message');
	}
	
	//创建会员反馈消息
	public function feedback($v){
		$rs=array(
			//'title'    => $v['title'],
			'phone'    => $v['phone'],
			'email'    => $v['email'],
			'memo'     => $v['memo'],
			'username' => $v['username'],
			'add_time' => time(),
			//'ip'       => $v['ip'],
			//'location' => $v['location'],
		);
		$this->db->insert('feedback',$rs);
		return $this->status(true,'OK');
	}
	//获取反馈信息
	public function getFeedback($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('feedback');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true, $rs);
	}
	//获取一条反馈
	public function getFeedId($id){
		$rs=$this->get_one('*',array('id'=>$id),'feedback');
		return $this->status(true,$rs);
	}
	//删除
	public function removeFeed($id){
		$this->db->where_in('id',explode(',', $id));
		$this->db->delete('feedback');
	}
	
	//创建报名信息
	public function saveEnroll($v){
		$rs=array(
			'type'=>$v['type'],
			'name'=>$v['name'],
			'phone'=>$v['phone'],
			'company'=>$v['company'],
			'job'=>$v['job'],
			'add'=>$v['add'],
			'add_time'=>time(),
		);
		$this->db->insert('enroll',$rs);
		return $this->status(true,'OK');
	}
	//获取报名信息
	public function getEnroll($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('enroll');
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true, $rs);
	}
	//获取一条报名
	public function getEnrollId($id){
		$rs=$this->get_one('*',array('id'=>$id),'enroll');
		return $this->status(true,$rs);
	}
	//删除报名
	public function removeEnroll($id){
		$this->db->where_in('id',explode(',', $id));
		$this->db->delete('enroll');
	}
	//积分规则
	public function scoreRule(){
		$rs=$this->get_all('*',array(),'user_scores_rule');
		return $this->status(true,$rs);
	}
	//保存积分规则
	public function saveScoreRule($ids,$jfs){
		foreach($ids as $k=>$v){
			$this->db->update('user_scores_rule',array('scores'=>$jfs[$k]),array('id'=>$v));
		}
	}
	
	//微博登录
	public function wbconnect($p){
		$arr=array(
			'username' => 'WB'.uniqid(),
			'openid'   => 'WB'.$p['id'],
			'password' => uniqid(),
			'nickname' => $p['screen_name'],
			'sex'      => $p['gender']=='m'?1:2,
			'address'  => $p['location'],
			'headimg'  => $p['avatar_large'],
		);
		return $this->_thirdPartyLogin($arr);
	}
	//QQ登录
	public function qqconnect($p){
		$arr=array(
			'username' => 'QQ'.uniqid(),
			'openid'   => $p['openId'],
			'password' => uniqid(),
			'nickname' => $p['nickname'],
			'sex'      => $p['gender']=='男'?1:2,
			'address'  => "$p[province] $p[city]",
			'headimg'  => $p['figureurl_2'],
		);
		return $this->_thirdPartyLogin($arr);
	}
	private function _thirdPartyLogin($row){
		$rs = $this->get_one('*',array('openid'=>$row['openid']),'user');
		if($rs==array()){//用户不存在，注册返回
			$a = $this->create($row);
			if($a['status']){//注册成功
				$rs = $row;
				$rs['id'] = $a['msg'];
				return $this->status(true,$rs);
			}
		}else{//用户存在，登录返回
			return $this->status(true,$rs);
		}
		return $this->status(false);
	}
	//监视微信扫描登录
	public function WXScan($pc=false){
		$f = ($pc?'':'../').'uploads/file/scan_'.$this->ci->session->userdata('qrSession').'.txt';
		$ticket = file_get_contents($f);
		if(!$ticket) return $this->status(true,array());
		$rs = $this->get_one('id,username',array('scan_ticket'=>$ticket),'user');
		if($rs!=array()){
			$this->db->update('user',array('scan_ticket'=>''),array('id'=>$rs['id']));
			unlink($f);
		}
		return $this->status(true,$rs);
	}
	//提现申请
	public function withdrawApply($username, $total){
		$row = $this->get_one('*',array('username'=>$username,'withdraw_money >'=>0),'user');
		if($row!=array()) return $this->status(2,'您已申请一笔提现，请等待完成！');
		$user=$this->get_one('*',array('username'=>$username),'user');
		$a = json_decode($user['account'],true); 
		if($a['type']=='alipay') $payment = array_pop($this->ci->system->getPayments(1,'../'));
		if($a['type']=='bank')   $payment = array_pop($this->ci->system->getPayments(2,'../'));
		$fee = $payment['fee']?$payment['fee']:0.00;
		if($total>$user['rebate_money']-$fee) return $this->status(2,"您的余额为$user[rebate_money]，提现手续费为".$fee."，申请失败！");
		$this->db->insert('user_withdraw',array(
			'username'=>$username,
			'sn'=>sprintf("%u",crc32(uniqid())),
			'total'=>$total,
			'status'=>1,
			'memo'=>'提现'.$total.'元',
			'addtime'=>time(),
			'fee'=>$fee,
			'payment'=>$a['type'],
			'account_info'=>$user['account'],
		));
		$this->db->update('user', array('withdraw_money'=>$total,'rebate_money'=>$user['rebate_money']-$total), array('id'=>$user['id']));
		return $this->status(3,'成功申请提现！');
	}
	public function getWithdrawList($tj=array(),$tj2=array(),$web='admin',$pagesize=12,$page=1){
		$this->open('user_withdraw');
		$tj2['join']='user';
		$tj2['on']='b.username=a.username';
		$tj2['a_fields']='a.account';
		$data=$web=='admin'? $this->get_list($tj,$tj2):$this->front_get_list($tj,$tj2,$pagesize,$page);
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
		foreach($rs['rows'] as $k=>$v){
			$rs['rows'][$k]['addtime']=date('Y-m-d H:i:s',$v['addtime']);
			foreach(json_decode($v['account'],true) as $i=>$s) $rs['rows'][$k][$i]=$s;
			if($v['status']==1) $rs['rows'][$k]['statusText']='申请中';
			if($v['status']==2) $rs['rows'][$k]['statusText']='<font color=red>已拒绝</font>';
			if($v['status']==3) $rs['rows'][$k]['statusText']='待付款';
			if($v['status']==4) $rs['rows'][$k]['statusText']='<font color=green>已提现</font>';
		}
	    return $this->status(true, $rs);
	}
	//更新申请状态
	public function updateWithdrawStatus($ids,$status,$msg=''){
		foreach(explode(',',$ids) as $id){
			$row = $this->get_one('*',array('id'=>$id),'user_withdraw');
			if($row==array()) continue;
			if($row['status']==1){
				if($status==2){//拒绝申请
					$this->db->update('user_withdraw',array('status'=>2,'msg'=>$msg,'operator'=>$this->ci->session->userdata('admin_name')),array('id'=>$id));
					$user = $this->get_one('*',array('username'=>$row['username']),'user');
					$this->db->update('user', 
						array('withdraw_money'=>0,'rebate_money'=>$user['rebate_money']+$row['total']),
						array('id'=>$user['id'])
					);
				}
				if($status==3){//通过申请
					$this->db->update('user_withdraw',array('status'=>3,'operator'=>$this->ci->session->userdata('admin_name')),array('id'=>$id));
				}
			}
		}
		if($status==2) return $this->status(false,'已拒绝申请！');
		if($status==3) return $this->status(true,'已通过申请！');
	}
	//确认提现
	public function confirmWithdraw($payment,$data){
		if($payment==1) $payText='alipay';
		if($payment==2) $payText='bank';
		$payments = array_pop($this->ci->system->getPayments($payment,'../'));
		if(!$data) return $this->status(false,'无效的参数');
		foreach($data as $v){
			$row = $this->get_one('*',array('sn'=>$v['sn']),'user_withdraw');
			$user = $this->get_one('*',array('username'=>$row['username']),'user');
			if($row==array()||$user==array()) continue;
			if($row['status']==3){
				$this->db->update('user_withdraw',array(
					'status'           => 4,
					'pay_sn'           => $v['pay_sn'],
					'pay_time'         => time(),
					'pay_method'       => $payText,
					'pay_account'      => $payments['seller_email'],
					'pay_bank'         => $payments['bank_name'],
					'pay_bank_address' => $payments['bank_address'],
				),array('id'=>$row['id']));
				$this->db->update('user', 
					array('withdraw_money'=>0,'withdraw_total'=>$user['withdraw_total']+$row['total']),
					array('id'=>$user['id'])
				);
			}
		}
		return $this->status(true,'成功提现!');
	}
	//转账
	public function transPay($method,$id){
		$rows = $this->get_all('*',array(),'user_withdraw',array('wherein'=>array('b.id'=>explode(',',$id)),'join'=>'user','on'=>'b.username=a.username','a_fields'=>'a.account'));
		if($rows==array()) exit('TRANSACTION FAILD! DUE TO INVALID REQUEST.');
		if($method=='alipay'){
			foreach($rows as $v){
				$a = json_decode($v['account'],true);
				$arr[]=array($v['sn'], $a['account'], $a['name'], $v['total'],$v['memo']);
				$this->db->update('user_withdraw',array('operator'=>$this->ci->session->userdata('admin_name')),array('sn'=>$v['sn']));
			}
			$this->ci->load->library('Huashang/alipay');
			$this->ci->alipay->transPay(WEB.'welcome/confirm_alipay',$arr);
		}
	}
	//人工付款
	public function manualPay($data){
		$row  = $this->get_one('*',array('sn'=>$data['id']),'user_withdraw');
		$user = $this->get_one('*',array('username'=>$row['username']),'user');
		$arr  = array(
			'pay_sn'          => $data['pay_sn'],
			'pay_method'      => $data['payment'],
			'pay_time'        => strtotime($data['pay_time']),
			'pay_account'     => $data['pay_account'],
			'operator'        => $this->ci->session->userdata('admin_name'),
			'status'          => 4,
		);
		if($data['pay_method']=='bank'){
			$arr['pay_bank']        = $data['pay_bank'];
			$arr['pay_bank_address']= $data['pay_bank_address'];
		}
		$this->db->update('user_withdraw',$arr,array('sn'=>$data['id']));
		$this->db->update('user', 
			array('withdraw_money'=>0,'withdraw_total'=>$user['withdraw_total']+$row['total']),array('id'=>$user['id'])
		);
		return $this->status(true,'成功提现!');
	}
	
	// 更新广告位排序
	public function update_gg_sort_order($id,$gg_sort_order){
		if(empty($id) || !is_numeric($id) || empty($gg_sort_order) || !is_numeric($gg_sort_order)){
			return false;
		}
		$row = array(
			'gg_sort_order'	=> $gg_sort_order,
		);
		$this->db->update('user',$row,array('id'=>$id));
		return true;
	}
	
	// 根据店铺名称查找店铺信息
	public function searchStoreByVender($keyword,$page=1,$pagesize=14){
		$like_arr['like']=array('vender'=>(string)urldecode($keyword));
		$like_arr['join']='user_info';
		$like_arr['on']='b.id = a.user_id';
		$like_arr['b_fields']='b.id as user_id,b.vender';
		$like_arr['a_fields']='a.sheng,a.shi,a.qu,a.logo';
		$tj_arr['type']='value-1';
		$dataq =array_pop($this->getlist($tj_arr,$like_arr,'web',$pagesize,$page));
		return $dataq;
	}
	
	function save($id,$row){
		if(empty($id) || !is_numeric($id) || empty($row) || !is_array($row)){
			return false;
		}
		$this->db->update('user',$row,array('id'=>$id));
		return true;
	}
	
	// 验证用户是否发布商
	public function IsBuy($id){
		if(empty($id) || !is_numeric($id)){
			return false;
		}
		$buy_info = $this->get_one('type',array('id' =>$id),$this -> table);
		if($buy_info['type'] ==2){
			return true;
		}else{
			return false;
		}
	}
	function isExistShop($shop_id){
		if(empty($shop_id) || !is_numeric($shop_id)){
			return false;
		}
		return $this -> get_one('id',array('id' => $shop_id,'type'=>1),$this -> table);
	}
	
	function getLogoByUserId($user_id){
		if(empty($user_id) || !is_numeric($user_id)){
			return false;
		}
		if($shop_info = $this -> get_one('logo',array('user_id' => $user_id),'user_info')){
			return $shop_info['logo'];
		}else{
			return false;
		}	
	}
	// 用户是否存在
	function isExistByUsername($username){
		if(empty($username)){
			return false;
		}
		if($this -> get_one('id',array('username' =>$username),$this -> table)){
			return true;
		}else{
			return false;
		}
	}
	// 修改密码
	public function changePass($phone,$pass){
		if(empty($phone) || empty($pass) || !is_numeric($phone)){
			return false;
		}
		return $this->db->update($this -> table,array('password' => md5($pass)),array('username'=>$phone));
	}
	
	// 获取刚入驻店铺
	public function getRecentList($limit=6){
		return $this->get_all('vender',array('type'=>1),$this ->table,array('order'=>'id desc','limit'=>$limit));
	}
}
?>